package com.maisha.utils;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

import org.junit.BeforeClass;
import org.junit.Test;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

public class CacheUtil {
	
	private static Cache<Object,Object> cache;
	
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		
		cache = CacheBuilder.newBuilder()
			       .maximumSize(1000)
			       .expireAfterWrite(1, TimeUnit.SECONDS).build();
		cache.put("a", 1);
	}
	
	@Test
	public void sss() {
		
		System.out.println(cache.getIfPresent("a"));
		
		try {
			int b = (Integer) cache.get("b", new Callable() {

				@Override
				public Object call() throws Exception {
					return getValue("b");
				}
				
			});
			System.out.println(b);
			System.out.println(cache.getIfPresent("b"));
			Thread.sleep(1000);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(cache.getIfPresent("a"));
		
	}
	
	private int getValue(String key) {
		if("b".equals(key)) {
			return 2;
		}
		
		return 0;
	}
}
